/**
 * Created by 陈熠 on 2017/6/21
 * email   :  228112142@qq.com
 * 公用模块
 */

//页面跳转
$(document).on('click', '*[lay-href]', function () {
    var othis = $(this)
        , href = othis.attr('lay-href')
        , text = othis.attr('lay-text')
        , router = layui.router();

    // admin.tabsPage.elem = othis;
    //admin.prevRouter[router.path[0]] = router.href; //记录上一次各菜单的路由信息
    //执行跳转
    var topLayui = parent === self ? layui : top.layui;
    topLayui.index.openTabsPage(href, text || othis.text());
});

//重写alert
window.alert = function (msg, callback) {
    parent.layer.alert(msg, function (index) {
        parent.layer.close(index);
        if (typeof(callback) === "function") {
            callback(index);
        }
    });
};

//重写confirm式样框
window.confirm = function (msg, callback) {
    parent.layer.confirm(msg, {btn: ['确定', '取消']},
        function () {//确定事件
            if (typeof(callback) === "function") {
                callback("ok");
            }
        });
};
//清空缓存
function resetCache(url) {
    var index = Loading.open(1, true);
    $.ajax({
        url: url,
        type: "post",
        async: true,
        dataType: "json",
        success: function (R) {
            if (R.code == 0) {
                parent.layer.msg('缓存清空成功 !', {icon: 1});
                parent.layer.close(index);
            } else {
                parent.layer.msg(R.msg, {icon: 5});
            }
        },
        error: function () {
            alert("系统繁忙");
        }
    });
}
//数据表格相关监听
layui.use('table', function () {
    var table = layui.table;

    //监听单元格编辑(排序)
    table.on('edit()', function (obj) {
        // 验证是否是数字
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        if(!$reg.onlyInt(value)){
            Msg.error("只能填写整数");
            $(this).val($(this).parent().text());
            return;
        }
        var _data=eval("({id:"+data.id+","+field+":"+value+"})");
        $.ajax({
            url: $(this).parent().attr("data-editUrl"),
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(_data),
            async: true,
            dataType: "json",
            success: function (R) {
                if (R.code === 0) {
                    $(".search-btn").click();
                    //刷新页面
                    parent.layer.msg('修改成功 !', {icon: 1});
                } else {
                    parent.layer.msg(R.msg, {icon: 5});
                }
            },
            error: function () {
                parent.layer.msg("系统繁忙", {icon: 5});
            }
        });
    });

    table.on('checkbox()', function (obj) {
        console.log(obj.checked); //当前是否选中状态
        console.log(obj.data); //选中行的相关数据
        console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
    });

    //监听表格复选框选择
    table.on('checkbox()', function (obj) {
        console.log(obj)
    });
    //监听工具条
    table.on('tool()', function (obj) {
        var data = obj.data;
        if (obj.event === 'info') {
            detailOne($(this).attr("lay-url"));
        } else if (obj.event === 'delete') {
            deleteOne($(this).attr("lay-url"), data.id);
        } else if (obj.event === 'edit') {
            editOne($(this).attr("lay-url"));
        }
    });


});

layui.use(['form'], function () {
    var form = layui.form || layui.form();
    //监听提交///保存或修改
    form.on('submit(submit)', function (data) {
        var url = $(this).attr("data-url");
        var pageId = $(this).attr("page-id");
        $.ajax({
            url: url,
            type: "post",
            contentType: "application/json",
            data: JSON.stringify(data.field),
            async: false,
            dataType: "json",
            success: function (R) {
                if (R.code == 0) {
                    $t.refresh(pageId);
                    //刷新页面
                    parent.layer.msg('操作成功 !', {icon: 1});
                } else {
                    parent.layer.msg(R.msg, {icon: 5});
                }
            },
            error: function () {
                alert("系统繁忙");
            }
        });
        return false;
    });

    //监听开关
    form.on('switch(status)', function (data) {
        //true勾选/false未勾选
        var id = $(data.elem).attr("data-id");
        var url = $(data.elem).attr("lay-url");
        var ids = [];
        ids.push(id);
        $.ajax({
            type: "post",
            url: url,
            contentType: "application/json",
            data: JSON.stringify(ids),
            async: false,
            dataType: "json",
            success: function (result) {
                if (result.code == 0) {
                    $(".search-btn").click();
                }
            },
            error: function () {
                parent.layer.msg("系统繁忙", {icon: 5});
            }
        });
    });


    //监听提交
    form.on('submit(search)', function (data) {
        var conditions = data.field;
        var index = parent.layer.msg('数据请求中', {
            icon: 16
            , time: -1
            , anim: -1
            , fixed: false
        });
        //查询时,将当前页码重置为1
        layui.use('table', function () {
            var table = layui.table;
            var tableId = $(data.elem).attr("table-id");
            //所获得的 tableIns 即为当前容器的实例
            table.reload(tableId, {
                where: conditions//设定异步数据接口的额外参数
                , page: {
                    curr: 1 //重新从第 1 页开始
                }
            });

        });

        parent.layer.close(index);
        return false;
    });

});

//获取数据表格选中的值
function getCheckData(tableId) {
    var checkStatus;
    layui.use('table', function () {
        var table = layui.table;
        checkStatus = table.checkStatus(tableId);
    });
    return checkStatus.data;
}

//获取数据表格选中值的id
function getCheckIds(tableId) {
    var ids=new Array();
    layui.use('table', function () {
        var table = layui.table;
        var   checkStatus = table.checkStatus(tableId);
        for(var i=0;i<checkStatus.data.length;i++){
            ids.push(checkStatus.data[i].id);
        }
    });
    return ids;
}

//选择一条记录
function getSelectedRow(table_id) {
    var checked = $("#" + table_id + " tbody .layui-form-checked");
    if (checked.length == 0) {
        parent.layer.msg("请选择一条记录", {icon: 5});
        //alert("请选择一条记录");
        return;
    }
    var selectedIDs = [];
    for (var i = 0; i < checked.length; i++) {
        var _this = $(checked[i]).prev();
        selectedIDs.push($(_this).attr("primary"));

    }
    if (selectedIDs.length > 1) {
        parent.layer.msg("只能选择一条记录", {icon: 5});
        //alert("只能选择一条记录");
        return;
    }
    return selectedIDs[0];
}

//选择多条记录
function getSelectedRows(table_id) {
    var checked = $("#" + table_id).next().find(".layui-table-body .layui-form-checked");
    if (checked.length == 0) {
        parent.layer.msg("至少选择一条记录");
        //alert("至少选择一条记录");
        return;
    }
    var selectedIDs = [];
    for (var i = 0; i < checked.length; i++) {
        var _this = $(checked[i]).prev();
        selectedIDs.push($(_this).attr("primary"));

    }
    return selectedIDs;
}

//重置按钮
$(function () {
    $("[type='reset']").click(function () {
        $(this).parents(".layui-form").find("input").val("");
        $(this).parents(".layui-form").find("select").val("");
        $(this).prev().click();
    });

});

/**
 * 详情
 * @param url
 */
function detailOne(url) {
    var width = "888px";
    if ($t.isMobile()) {
        width = "80%";
    }
    parent.layer.open({
        type: 2,
        title: '详情',
        shadeClose: false,
        shade: [0.3, '#000'],
        maxmin: true, //开启最大化最小化按钮
        area: [width, '80%'],
        content: url
    });

}


/**跳转到添加页面
 * @param table_id 表格id
 * @param url      请求地址
 */
function addPage(url,id) {
    var width = "700px";
    if ($t.isMobile()) {
        width = "80%";
    }
    parent.layer.open({
        id:id,
        type: 2,
        title: '添加',
        shadeClose: false,
        shade: [0.3, '#000'],
        maxmin: true, //开启最大化最小化按钮
        area: [width, '80%'],
        content: url
    });
}
/**跳转到修改页面
 * @param table_id 表格id
 * @param url      请求地址
 */
function editPage(tableId, url) {
    var tableData = getCheckData(tableId);
    if (tableData.length === 0) {
        Msg.info("请选择一条数据");
        return;
    }
    if (tableData.length > 1) {
        Msg.info("只能选择一条数据");
        return;
    }
    var width = "700px";
    if ($t.isMobile()) {
        width = "80%";
    }

    if (tableData[0].id) {
        parent.layer.open({
            type: 2,
            title: '修改',
            shadeClose: false,
            shade: [0.3, '#000'],
            maxmin: true, //开启最大化最小化按钮
            area: [width, '80%'],
            content: url + "/" + tableData[0].id
        });
    }
}

/**
 * 修改
 * @param url 请求地址
 * @param id  选中的id
 */
function editOne(url) {
    var width = "700px";
    if ($t.isMobile()) {
        width = "80%";
    }
    parent.layer.open({
        type: 2,
        title: '修改',
        shadeClose: false,
        shade: [0.3, '#000'],
        maxmin: true, //开启最大化最小化按钮
        area: [width, '80%'],
        content: url
    });
}

/**
 * 批量删除
 * @param table_id 表格id
 * @param url      请求地址
 */
function deleteBatch(msg, tableId, url) {
    //获取选中的id
    var ids = getCheckIds(tableId);
    if (ids.length === 0) {
        Msg.info("至少选择一条数据");
        return;
    }
    if (ids != null) {
        confirm("确认" + msg + "？", function () {
            $.ajax({
                type: "post",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(ids),
                async: false,
                dataType: "json",
                success: function (R) {
                    var msg = R.msg || "操作成功!";
                    if (R.code == 0) {
                        $(".search-btn").click();
                        parent.layer.msg(msg, {icon: 1});
                    } else {
                        parent.layer.msg(R.msg, {icon: 5});
                    }
                },
                error: function () {
                    parent.layer.msg("系统繁忙", {icon: 5});
                }
            });
        });
    }

}
/**
 * 删除一条数据
 * @param url 请求地址
 * @param id  选中的id
 */
function deleteOne(msg, url, id) {
    var ids = [];
    ids.push(id);
    //获取选中的id
    confirm("确认" + msg + "？", function () {
        $.ajax({
            type: "post",
            url: url,
            contentType: "application/json",
            data: JSON.stringify(ids),
            async: false,
            dataType: "json",
            success: function (result) {
                var msg = result.msg || "操作成功!";
                if (result.code == 0) {
                    $(".search-btn").click();
                    parent.layer.msg(msg, {icon: 1});
                } else {

                    parent.layer.msg(result.msg, {icon: 5});
                }
            },
            error: function () {
                parent.layer.msg("系统繁忙", {icon: 5});
            }
        });
    });

}


/**
 * 批量启用或禁用
 * @param msg      提示信息(启用或禁用)
 * @param table_id 表格id
 * @param url      请求地址
 */
function updateState(msg, tableId, url) {
    //获取选中的id
    var ids = getCheckIds(tableId);
    if (ids.length === 0) {
        Msg.info("至少选择一条数据");
        return;
    }
    if (ids != null) {
        confirm("确认" + msg + "？", function () {
            $.ajax({
                type: "post",
                url: url,
                contentType: "application/json",
                data: JSON.stringify(ids),
                async: false,
                dataType: "json",
                success: function (result) {
                    var msg = result.msg || "操作成功!";
                    if (result.code == 0) {
                        $(".search-btn").click();
                        parent.layer.msg(msg, {icon: 1});
                    } else {
                        parent.layer.msg(result.msg, {icon: 5});
                    }
                },
                error: function () {
                    parent.layer.msg("系统繁忙", {icon: 5});
                }
            });
        });
    } else {
        parent.layer.msg("至少选择一条记录", {icon: 5});
        //alert("至少选择一条记录");
        return;
    }

}

/**
 * 启用或禁用一条数据
 * @param msg 提示信息
 * @param url 请求地址
 * @param id  选中的id
 */
function updateStateOne(msg, url, id) {
    var ids = [];
    ids.push(id);
    confirm("确认" + msg + "？", function () {
        $.ajax({
            type: "post",
            url: url,
            contentType: "application/json",
            data: JSON.stringify(ids),
            async: false,
            dataType: "json",
            success: function (result) {
                var msg = result.msg || "操作成功!";
                if (result.code == 0) {
                    $(".search-btn").click();
                    parent.layer.msg(msg, {icon: 1});
                } else {
                    parent.layer.msg(result.msg, {icon: 5});
                }
            },
            error: function () {
                parent.layer.msg("系统繁忙", {icon: 5});
            }
        });
    });

}


//更多查询条件监听事件
layui.use(['form'], function () {
    var form = layui.form || layui.form();
    //监听提交
    form.on('submit(moreSearch)', function (data) {
        if ($(this).children().hasClass("fa-chevron-down")) {
            //显示更多条件
            $(this).parents(".layui-form").find(".more-search").show();
            //修改更多按钮图标
            $(this).html('<i class="fa fa-chevron-up">&nbsp;</i>收起');
        } else {
            //显示更多条件
            $(this).parents(".layui-form").find(".more-search").hide();
            //修改更多按钮图标
            $(this).html('<i class="fa fa-chevron-down">&nbsp;</i>更多');
        }

        return false;
    });
});

